package net.melon.stock.inst.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.esj.basic.dao.querybuilder.QueryBuilder;
import net.esj.basic.exception.MelonException;
import net.esj.basic.service.impl.DefaultServiceImpl;
import net.esj.basic.utils.Assert;
import net.melon.order.pojo.Order;
import net.melon.product.pojo.Product;
import net.melon.stock.inst.service.StockService;
import net.melon.stock.pojo.Stock;

@Service
public class StockServiceImpl extends DefaultServiceImpl implements StockService{

	@Transactional
	@Override
	public void addStock(Stock entity) {
		save(entity);
		Product product = get(entity.getProduct().getId(), Product.class);
		product.setStock(product.getStock() + entity.getCount());
		update(product);
	}

	@Transactional
	@Override
	public void updateStock(Stock entity) {
		Stock p = get(entity.getId(), Stock.class);
		Product product = get(p.getProduct().getId(), Product.class);
		product.setStock(product.getStock() + (entity.getCount() - p.getCount() ));
		update(product);
		update(p);
	}

	@Override
	public List<Stock> getStockListByProductId(String id) {
		QueryBuilder<Stock> qb = createQueryBuilder(Stock.class);
		qb.eq("product.id", id).notEq("count", 0);
		return queryListByQueryBuilder(qb);
	}

	@Override
	public Stock getStockByProductIdAndRegionId(String productId,
			String regionId) {
		QueryBuilder<Stock> qb = createQueryBuilder(Stock.class);
		qb.eq("product.id", productId).eq("regionId", regionId);
		return (Stock) queryFirst(qb);
	}

	@Override
	public boolean checkAddStock(Stock entity) {
		QueryBuilder<Stock> qb = createQueryBuilder(Stock.class);
		qb.eq("regionId", entity.getRegionId()).eq("product.id", entity.getProduct().getId());
		if(queryCountByQueryBuilder(qb)==0){
			return true;
		}
		return false;
	}

	@Override
	public void deleteStock(Integer id) {
		Stock stock = get(id, Stock.class);
		Assert.notNull(stock);
		QueryBuilder<Order> qb = createQueryBuilder(Order.class);
		qb.eq("region.id", Long.valueOf(stock.getRegionId())).eq("product", stock.getProduct());
		if(queryCountByQueryBuilder(qb)>0){
			throw new MelonException("该库存下存在订单，不能删除");
		}else{
			delete(stock);
		}
	}

	@Override
	public void reduceStockByOrder(Order order) {
		Stock stock = getStockByProductIdAndRegionId(order.getProduct().getId(), String.valueOf(order.getRegion().getId()));
		if(stock.getCount()>0){
			stock.setCount(stock.getCount() - 1);
			update(stock);
		}else{
			throw new MelonException("库存不足"); 
		}
		
	}
	
}
